import { useEffect } from "react";
import { useReactive } from "ahooks";
import { useModel } from "umi";
import { useOrganization } from "@share-code/public";

export default function organizationModal() {
    const { remoteData } = useModel("global");
    const { loginInfo } = useModel("person.info");
    const { loadLocalOrganizationInfo, loadRemoteOrganizationInfo, loadOrganizationGatewayUrl } = useOrganization(remoteData);

    const state = useReactive({
        organizationUuid: window.organizationUuid,
        organizationInfo: {},
        remoteOrganizationInfo: {},
        gatewayUrl: "",
    });

    const loadData = async () => {
        state.organizationInfo = (await loadLocalOrganizationInfo(window.organizationUuid)) || {};
        if (loginInfo?.authCenterUrl) {
            state.remoteOrganizationInfo = (await loadRemoteOrganizationInfo(loginInfo.authCenterUrl, window.organizationUuid)) || {};
            state.gatewayUrl = (await loadOrganizationGatewayUrl(loginInfo.authCenterUrl, state.organizationUuid)) || "";
        }
    };

    useEffect(() => {
        loadData();
    }, [loginInfo]);

    const setOrganizationStateValue = (obj) => {
        for (let key in obj) {
            state[key] = obj[key];
        }
    };

    return {
        ...state,
        setOrganizationStateValue,
    };
}
